<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Messages_mod extends CI_Model
{   
    
    private $_dbTableMessages = 'messages';
    private $_dbTableUsers = 'users';
    private $_dbTableImages = 'images';
    private $_dbTableSupport = 'support';
    private $_dbTableActivity = 'mod_activity';
    private $_dbTableIns = 'mod_ins';
    private $_dbTableLogOnline = 'log_online';
    private $_emailConfig;
    /**
     *  class sonstructor
     */
    function __construct() 
	{
		// Call the Model constructor
        parent::__construct();
        
        $this->load->library('email');
  
        // define terms for emails
		$this->_emailConfig['mailtype'] = 'txt';
        $this->_emailConfig['useragent'] = 'PHP CodeIgniter';  
	}
    
    /**
     * for Library Modules
     * @return int - num unread messages
     * @throws Exception - SQL Query errors
     */
    public function getNumUnreadMessages()
    {
        $this->db->from($this->_dbTableMessages)
                 ->where('to',$this->session->userdata('user_id'))
                 ->where('seen',0);
        $num_unread_messages = $this->db->count_all_results();
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
       
        return $num_unread_messages;
    }
    
    public function getMyConversationList()
    {
        $id = $this->session->userdata('user_id');
        $sql = "
              SELECT * FROM
              (SELECT {$this->_dbTableMessages}.id,
                       {$this->_dbTableMessages}.to,
                       {$this->_dbTableMessages}.from,                       
                       {$this->_dbTableMessages}.content,
                       {$this->_dbTableMessages}.time,
                       {$this->_dbTableMessages}.seen,
                       {$this->_dbTableUsers}.username,
                       {$this->_dbTableUsers}.name, 
                       IF( {$this->_dbTableMessages}.to = $id ,`from`,`to`) as `image_dir`,
                       ( SELECT name  FROM {$this->_dbTableImages} WHERE `private`=0 and `user_id`= IF( {$this->_dbTableMessages}.to = $id ,`from`,`to`) ORDER BY main desc LIMIT 0,1 ) as image_name
                FROM  {$this->_dbTableMessages}, {$this->_dbTableUsers}
                WHERE 
                      {$this->_dbTableUsers}.id =  IF( {$this->_dbTableMessages}.to = $id ,`from`,`to`)
                      AND
                      (                       
                        {$this->_dbTableMessages}.to = {$id}  AND `del_to` = 0
                      OR  
                        {$this->_dbTableMessages}.from = {$id}  AND `del_from` = 0 
                      )                      
                ORDER BY {$this->_dbTableMessages}.seen ASC, UNIX_TIMESTAMP({$this->_dbTableMessages}.time) DESC 
               ) AS sub                       
                GROUP BY `username` 
                ORDER BY `seen` ASC, UNIX_TIMESTAMP(`time`) DESC 
                ;
               ";
                
                
                
        $query = $this->db->query($sql);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = $query->result();
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;
    }
    
    
    public function getMessages( $from, $seen = true)
    {
        $me = $this->session->userdata('user_id');
        $where = "
             /* one koje sam primio  */
            ( ({$this->_dbTableMessages}.to = {$me} AND {$this->_dbTableMessages}.from = {$from}) AND `del_to` = 0 )
            OR  /* i one koje sam poslao */
            ( ({$this->_dbTableMessages}.to = {$from} AND {$this->_dbTableMessages}.from = {$me}) AND `del_from` = 0 )
           
        ";
        if( $seen )
        {
          // Postavi da su sve poruke procitane koje su meni poslate od tog usera, jer ih sad gledam (prikazujem)
          $sql_update = "UPDATE {$this->_dbTableMessages} 
                         SET seen = 1 
                         WHERE (
                                   {$this->_dbTableMessages}.to = {$me} /* one koje su poslate meni */
                                AND 
                                   {$this->_dbTableMessages}.from = {$from} /* od tog korisnika */
                                )
                                /*OR 
                                (
                                   {$this->_dbTableMessages}.from = {$me} 
                                AND 
                                   {$this->_dbTableMessages}.to = {$from} 
                                )
                                */
                         ;  
                        ";
          $query = $this->db->query($sql_update);        
          //echo $this->db->last_query();
          $errors = $this->db->_error_message();
          if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
          } else { }
        }
            
        // Preuzmi sve poruke    
        $sql = "SELECT {$this->_dbTableMessages}.*                       
                       FROM {$this->_dbTableMessages}
                       WHERE {$where}
                       ORDER BY {$this->_dbTableMessages}.time ASC;
        ";
        $query = $this->db->query($sql);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = $query->result();
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;
    }
    
    
    public function getSupportMessages()
    {
        $me = $this->session->userdata('user_id');
        $where = "
             /* one koje sam primio  */
            {$this->_dbTableSupport}.to = {$me}
            OR  /* i one koje sam poslao */
            {$this->_dbTableSupport}.from = {$me} 
           
        ";
        // Preuzmi sve poruke    
        $sql = "SELECT {$this->_dbTableSupport}.*                       
                       FROM {$this->_dbTableSupport}
                       WHERE {$where}
                       ORDER BY {$this->_dbTableSupport}.time DESC;
        ";
        $query = $this->db->query($sql);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = $query->result();
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;    
    }
    
    /**
     *  AJAX
     */
    public function sendMessage($from,$to,$message)
    {
        $query = $this->db->select('coins')
                          ->where('id',$from)
                          ->get($this->_dbTableUsers);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if ($query->num_rows() == 1) {
          $coins = $query->row()->coins;          
          $query->free_result();          
        } else {
          //$coins = 0;
          return false;
        }        
        $message_cost = $this->config->item('message_cost');
        if( $coins >= $message_cost )
        {
          // Smanji kredit 
          $sql = "UPDATE {$this->_dbTableUsers} SET `coins`=`coins`-{$message_cost} WHERE `id`={$from}; ";
          $query = $this->db->query($sql);
          
          $errors = $this->db->_error_message();
          if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
          } else { }
          
          if ($this->db->affected_rows() != 1) {
              return false;
              //$query->free_result();
          } else { }
        }
        else
        {
          return -2; // Nema para za poruku
        }
        
        $data = array(
            'from'=>$from,
            'to'=>$to,
            'content'=>$message
        );
        $query = $this->db->insert($this->_dbTableMessages,$data);
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if ($this->db->affected_rows() == 1) {
          $result = 1;
          if($this->_checkFakeUser($to))
              $this->_updateModActivity($from, $to);
          if( ! $this->_isOnline($to) ) // Ako nije online posalji mail
            $this->_sendMessageToEmail($from,$to);
          
          //$query->free_result();
        } else {
          $result = false;
        }
        
        return $result;
    }
    
    private function _isOnline($id)
    {
      $query = $this->db->select('user_id')
                        ->from($this->_dbTableLogOnline)
                        ->where("user_id",$id)
                        ->get();
      if( $query->num_rows() > 0 )
        return true;
      else
        return false;
    }
    
    public function sendSupportMessage($from,$message)
    {
        
        
        $data = array(
            'from'=>$from,
            'to'=>1,
            'content'=>$message
        );
        $query = $this->db->insert($this->_dbTableSupport,$data);
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if ($this->db->affected_rows() == 1) {
          $result = true;
          //$query->free_result();
        } else {
          $result = false;
        }

        return $result;
    }
    public function remove_conversation($from_id,$to_id)
    {
//        $sql = "DELETE FROM {$this->_dbTableMessages}
//                WHERE (`from` = $from_id AND `to` = $to_id)
//                      OR
//                      (`from` = $to_id AND `to` = $from_id)
//                ;
//               ";
        //$this->db->where('from',$from_id)->delete($this->_dbTableMessages);
        $my_id = $this->session->userdata('user_id');
                
        $you_id = ($from_id==$my_id)?$to_id:$from_id;
        
        $sql = "UPDATE {$this->_dbTableMessages} 
                SET  `del_from` = 1 
                WHERE `from` = $my_id AND `to` = $you_id ;
               ";
        $this->db->query($sql);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {         
          throw new Exception("SQL Error: " . $errors);
          return false;
        } else { }
        
        $sql = "UPDATE {$this->_dbTableMessages} 
                SET  `del_to` = 1 
                WHERE  `from` = $you_id AND `to` = $my_id ;
               ";
        $this->db->query($sql);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
          return false;
        } else { }
        
//        if ($this->db->affected_rows() > 0) {
//          $result = true;
//          //$query->free_result();
//        } else {
//          $result = false;
//        }
//
//        return $result;
        return true;
    }
    
    
    private function _sendMessageToEmail($from,$to)            
    {
      $query = $this->db->select('username,name,email')
                        ->from($this->_dbTableUsers)
                        ->where('id',$from)
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() == 1) {
        $user_from = $query->row();
        $query->free_result();
      } else {
        $user_from = NULL;
        return;
      }
      
      $query = $this->db->select('username,name,email,is_fake')
                        ->from($this->_dbTableUsers)
                        ->where('id',$to)
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() == 1) {
        $user_to = $query->row();        
        $query->free_result();
      } else {
        $user_to = NULL;
        return;
      }
      
      if( $user_to->is_fake == 1 )
        return true; // Ne salji mail fake useru
      
      //$from_name = ($user_from->name!="")?$user_from->name:$user_from->username;
      $from_name = $user_from->username;
      
      $message = sprintf(lang('you_have_message'),$from_name);

      $this->email->clear();
      $this->email->initialize($this->_emailConfig);

      $this->email->to($user_to->email);

      //$this->email->from($user_from->email);
      $this->email->from($this->config->item('mail_noreply'));
      $this->email->subject(lang('you_have_message_subject'));
      $this->email->message($message);

      if (!$this->email->send()) {
         // Generate error (by CI)
         throw new Exception("Email cannot be sent. Try again or contact admin!");
         //echo $this->email->print_debugger();
         return false;
      }          
      
    }
    private function _checkFakeUser($to){
        $this->db->select('id');
        $this->db->where('id',$to);
        $this->db->where('is_fake',1);
        $this->db->from($this->_dbTableUsers);
        $query=  $this->db->get();
        if ($query->num_rows() > 0) {
        $query->free_result();
        return TRUE;
      } else {
        return FALSE;
      }
    }
    private function _updateModActivity($from, $to){
        $where=$where="({$this->_dbTableActivity}.fake_user_id=".$to." AND {$this->_dbTableActivity}.user_id=".$from." AND {$this->_dbTableActivity}.start_time=( SELECT MAX({$this->_dbTableActivity}.start_time) "
           ."FROM {$this->_dbTableActivity} WHERE {$this->_dbTableActivity}.fake_user_id=".$to." AND {$this->_dbTableActivity}.user_id=".$from."))";
        $this->db->select('mod_id');
        $this->db->where($where);
        $this->db->from($this->_dbTableActivity);
        $query=  $this->db->get();
        if ($query->num_rows() == 1) { // ONE ROW
          $result = $query->row(); // RETURN ONE ROW object
          $query->free_result();
          $mod_id=$result->mod_id;
          
          $this->db->select('ins, date');
          $this->db->from($this->_dbTableIns);
          $this->db->where('mod_id', $mod_id);
          $this->db->where("DATE({$this->_dbTableIns}.date) = DATE(NOW())");
          $query=  $this->db->get();
          if ($query->num_rows() >0) {
               $result = $query->row(); // RETURN ONE ROW object
               $query->free_result();
               $ins=$result->ins;
               $date=$result->date;
               $this->db->update($this->_dbTableIns, array('ins'=>$ins+1), array('mod_id'=>$mod_id, 'date'=>$date));
          }
          else{
              $this->db->insert($this->_dbTableIns, array('mod_id'=>$mod_id,'ins'=>1));
          }
       } else {
          $result = NULL;
        }
        
    }
    
}// end class Messages_mod

/*
      $query = $this->db->select('*')
                        ->from()
                        ->where()
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() > 0) {
        $result = $query->result();
        $query->free_result();
      } else {
        $result = NULL;
      }

      return $result;
 */

// end file: application/models/messages_mod.php

?>